<?php
class Cp_UserController extends Pidguin_Controller_Cp_Action
{	
	public function indexAction()
	{
		$this->view->users = Model_User::getInstance()->fetchAll();
	}
	
	public function editAction()
	{
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('User ID is not set');
		}
		 
		$m = Model_User::getInstance();
		$select = $m->select()->where(Model_User::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = $m->fetchRow($select);
		 
		if (!$row) {
			throw new Zend_Controller_Action_Exception('User not found');
		}
		
		$_inGroups = $row->findDependentRowset('Model_UserGroup');
		$inGroups = array();
		if (count($_inGroups)) {
			foreach ($_inGroups as $group) {
				$_r = $group->findParentRow('Model_Groups');
				$inGroups[] = array('groupId' => $_r->id);
			}
		}
		
		$this->view->user = $row;
		$this->view->groups = Model_Groups::getInstance()->fetchAll();
		$this->view->inGroups = Zend_Json::encode($inGroups);
	}
	
	public function editSaveAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('User ID is not set');
		}
	
		if (!$this->_getParam('login')) {
			throw new Zend_Controller_Action_Exception('Login is not set');
		}
	
		if (!preg_match('/[a-z0-9_\.]*/i', $this->_getParam('login'))) {
			throw new Zend_Controller_Action_Exception('Login incorrect');
		}
	
		if (!$this->_getParam('name')) {
			throw new Zend_Controller_Action_Exception('name is not set');
		}
	
		if (!preg_match('/[a-zа-я0-9_\s\-\.]*/i', $this->_getParam('name'))) {
			throw new Zend_Controller_Action_Exception('Name incorrect');
		}
	
		if ($this->_getParam('email') && !preg_match('/^([a-zA-Z_\-\.]+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})$/', $this->_getParam('email'))) {
			$this->_helper->json(array('status' => 'error', 'type' => 'email', 'message' => 'Не верный формат e-mail'));
		}
		
		$model = Model_User::getInstance();
		$select = $model->select()->where(Model_User::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = $model->fetchRow($select);
		
		if (!$row) {
			throw new Zend_Controller_Action_Exception('User not found');
		}
		
		$row->login = $this->_getParam('login');
		$row->name = $this->_getParam('name');
		$row->email = $this->_getParam('email');
		if ($this->_getParam('password')) {
			$row->password = sha1(md5($this->_getParam('password'), true));
		}
		$row->hash = md5($row->login . $row->name . $row->password);
		
		if (count($this->_getParam('groups')) <= 0) {
			$this->_helper->json(array('status' => 'error', 'type' => 'group', 'message' => 'Пожалуйста, укажите хотя бы одну группу'));
		}
		
		$groupsUser = $row->findDependentRowset('Model_UserGroup');
		if (count($groupsUser)) {
			foreach ($groupsUser as $userGroup) {
				$userGroup->delete();
			}
		}
		
		foreach ($this->_getParam('groups') as $groupId) {
			$gr = Model_UserGroup::getInstance()->createRow();
			$gr->user_id = $row->id;
			$gr->group_id = $groupId;
			$gr->save();
		}
		$row->save();
		$this->_helper->json(array('status' => 'ok'));
	}
	
	public function deleteAction()
	{
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('User id is not set');
		}
		
		if ($this->_getParam('id') == '1' || 
				$this->_getParam('id') == '2') {
			throw new Zend_Controller_Action_Exception('You can not delete system user');
		}
	
		$m = Model_User::getInstance();
		$select = $m->select()->where(Model_User::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = $m->fetchRow($select);
		if (!$row) {
			throw new Zend_Controller_Action_Exception('User not found');
		}
		$row->delete();
		$this->_redirect('/cp/user');
	}
	
	public function createAction()
	{
		$this->view->groups = Model_Groups::getInstance()->fetchAll();
	}
	
	public function createSaveAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
	
		if (!$this->_getParam('login')) {
			throw new Zend_Controller_Action_Exception('Login is not set');
		}
	
		if (!preg_match('/[a-z0-9_\.]*/i', $this->_getParam('login'))) {
			throw new Zend_Controller_Action_Exception('Login incorrect');
		}
	
		if (!$this->_getParam('name')) {
			throw new Zend_Controller_Action_Exception('name is not set');
		}
	
		if (!preg_match('/[a-zа-я0-9_\s\-\.]*/i', $this->_getParam('name'))) {
			throw new Zend_Controller_Action_Exception('Name incorrect');
		}
		
		if (!$this->_getParam('password')) {
			throw new Zend_Controller_Action_Exception('Password is not set');
		}
	
		if ($this->_getParam('email') && !preg_match('/^([a-zA-Z_\-\.]+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})$/', $this->_getParam('email'))) {
			$this->_helper->json(array('status' => 'error', 'type' => 'email', 'message' => 'Не верный формат e-mail'));
		}
		
		$model = Model_User::getInstance();
		$select = $model->select()->where(Model_User::getDefaultAdapter()->quoteInto('login = ?', $this->_getParam('login')));
		$row = $model->fetchRow($select);
		
		if ($row) {
			$this->_helper->json(array('status' => 'error', 'type' => 'login', 'message' => 'Пользователь с логином <b>' . $this->_getParam('login') . '</b> уже создан'));
		}
		$row = $model->createRow();
		$row->login = $this->_getParam('login');
		$row->name = $this->_getParam('name');
		$row->email = $this->_getParam('email');
		$row->password = sha1(md5($this->_getParam('password'), true));
		$row->hash = md5($row->login . $row->name . $row->password);
		
		if (count($this->_getParam('groups')) <= 0) {
			$this->_helper->json(array('status' => 'error', 'type' => 'group', 'message' => 'Пожалуйста, укажите хотя бы одну группу'));
		}
		$row->save();		
		foreach ($this->_getParam('groups') as $groupId) {
			$gr = Model_UserGroup::getInstance()->createRow();
			$gr->user_id = $row->id;
			$gr->group_id = $groupId;
			$gr->save();
		}
		$this->_helper->json(array('status' => 'ok'));
	}
}